package com.rtsapp.server.logger.format;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by admin on 16-2-27.
 */
public class StackTrace {

    private static final String NEW_LINE = "\r\n";

    public static void getStackTrace(StringBuilder sb, Throwable ex) {


        Set<Throwable> enclosedThrowables = new HashSet<>();

        sb.append("\r\n");

        printEnclosedStackTrace(sb, ex, enclosedThrowables);

    }


    private static void printEnclosedStackTrace(StringBuilder sb, Throwable ex, Set<Throwable> enclosedThrowables) {

        if (enclosedThrowables.contains(ex)) {
            return;
        }

        enclosedThrowables.add(ex);


        sb.append(ex);
        sb.append("\r\n");
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement traceElement : trace) {
            sb.append("\tat " + traceElement);
            sb.append("\r\n");
        }

        // Print suppressed exceptions, if any
        for (Throwable se : ex.getSuppressed()) {
            sb.append("suppressed  : ");
            printEnclosedStackTrace(sb, se, enclosedThrowables);
        }

        // Print cause, if any
        Throwable cause = ex.getCause();
        if (cause != null) {
            sb.append("cause by : ");
            printEnclosedStackTrace(sb, cause, enclosedThrowables);
        }

    }


    public static String getStackTrace(Throwable ex) {
        StringBuilder sb = new StringBuilder();
        getStackTrace(sb, ex);
        return sb.toString();
    }

    
}
